<?php

namespace app\api\controller;

use app\admin\model\PkAnswer;
use app\admin\model\reciting\Mission;
use app\admin\model\RecitingQuestionAnswer;
use app\admin\model\RecitingWordsAnwserLog;
use app\api\model\Homework;
use app\admin\model\Words;
use app\admin\model\WordsDetails;
use app\admin\model\WordsReviewLog;
use app\api\model\BrushWords;
use app\api\model\RecitingWordsLog;
use app\api\model\TextBooks;
use app\api\model\UserRecitingPlan;
use app\common\controller\Api;
use think\Db;
use think\Exception;
use think\Request;
use OSS\OssClient;
use OSS\Core\OssException;

class Answer extends Api
{
    //如果$noNeedLogin为空表示所有接口都需要登录才能请求
    //如果$noNeedRight为空表示所有接口都需要验证权限才能请求
    //如果接口已经设置无需登录,那也就无需鉴权了
    //
    // 无需登录的接口,*表示全部
    protected $noNeedLogin = [];
    // 无需鉴权的接口,*表示全部
    protected $noNeedRight = ['*'];

    private $wordsDetails;

    private $recitingWordsLog;

    private $words;

    public function __construct(Request $request = null)
    {
        parent::__construct($request);

        $this->words = new Words();
        $this->recitingWordsLog = new WordsReviewLog();
        $this->wordsDetails = new WordsDetails();
    }

    public function upload()
    {
        try {
            $file = request()->file('files');
            if(!$file){
                $this->error('上传文件不能为空');
            }
            $filename = $file->getInfo();
            $config = get_addon_config('alioss');
            //获取oss实例bucket
            $ossClient = new OssClient($config['accessKeyId'], $config['accessKeySecret'], $config['endpoint']);
            $bucket = $config['bucket']; //创建的项目
            $object = $filename['name']; //文件名
            $res = $ossClient->uploadFile($bucket,$object,$file->getRealPath());
            $this->success('上传成功',['url'=>$res['info']['url']]);
        } catch (OssException $e) {
            $this->error($e->getMessage());
        }
    }

    public function wordReviewLogSave()
    {
        $id = request()->post('id');
        $wid = request()->post('wid');

        if (!$id || !$wid)
            $this->error('参数有误');

        $detailInfo = $this->wordsDetails->where([
            'id' => $id
        ])->find();
        $status = "1";
        if ($detailInfo->wId != $wid)
            $status = "0";

        // 判断该单词是否已经答过
        $has = $this->recitingWordsLog->where([
            'user_id' => $this->auth->id,
            'wid' => $wid,
        ])->find();
        if ($has) {
            $has->wd_id = $id;
            $has->status = $status;
            $has->save();
        } else {
            $data = [
                'user_id' => $this->auth->id,
                'wid' => $wid,
                'wd_id' => $id,
                'version_id' => $detailInfo->versionId,
                'status' => $status
            ];

            $this->recitingWordsLog->save($data);
        }

            $this->success('成功', $status);
    }

    public function wordPkAnswer()
    {
        $param = request()->param();
        $id = $param['id'];
        $wid = $param['wid'];
        if (!$id || !$wid || !isset($param['pk_id'])){
            $this->error('参数有误');
        }

        $detailInfo = $this->wordsDetails->where([
            'id' => $id
        ])->find();
        $status = "1";
        if ($detailInfo->wId != $wid)
            $status = "0";
        //保存pk数据信息,返回正确还是错误，如果是最后一题返回本次PK结果
        (new PkAnswer())->insert([
            'pk_id'=>$param['pk_id'],
            'user_id'=>$this->auth->id,
            'wid' => $wid,
            'wd_id' => $id,
            'version_id'=>$detailInfo->versionId,
            'status'=>$status,
        ]);
        $this->success('成功', $status);
    }

    public function getPkResult()
    {
        $param = request()->param();
        $userList = PkAnswer::alias('a')->join('user b','a.user_id=b.id')->where(['pk_id'=>$param['pk_id']])
            ->field('a.user_id,b.nickname,b.avatar,sum(a.status) as score')
            ->group('a.user_id')
            ->select();
        $list = PkAnswer::alias('a')->join('words_details b','a.wd_id=b.id')
            ->where(['pk_id'=>$param['pk_id']])
            ->field('a.status,a.user_id,b.words,b.pretations')
            ->order('a.id asc')->select();

        $userGroup = [];
        foreach ($userList as $v) {
            if($v['user_id']==$this->auth->id){
                $userGroup['self']=$v;
            } else{
                $userGroup['rival']=$v;
            }
        }
        $this->success('成功', ['userList'=>$userGroup,'list'=>$list]);
    }


    /**
     * 刷单词保存
     * @return void
     */
    public function washWordsSave()
    {
        $id = request()->post('id');
        $wid = request()->post('wid');
        $param = request()->param();

        if (!$id || !$wid)
            $this->error('参数有误');

        $detailInfo = $this->wordsDetails->where([
            'id' => $id
        ])->find();
        // 判断该单词是否已经答过
        $has = RecitingWordsAnwserLog::where([
            'user_id' => $this->auth->id,
            'wid' => $wid,
        ])->find();
        if ($has) {
            $has->wd_id = $id;
            $has->score = $param['score']??0;
            $has->save();
        } else {
            $data = [
                'user_id' => $this->auth->id,
                'wid' => $wid,
                'wd_id' => $id,
                'version_id' => $detailInfo->versionId,
                'score' => $param['score']??0
            ];
            (new RecitingWordsAnwserLog())->save($data);
        }

        $this->success('成功', []);
    }



    public function getMissionHistory()
    {
        $param = request()->param();
        if(empty($param['month'])){
            $param['month'] = 1;
        }
        $missionInfo = [];
        $missionTxt = [
            1=>'听说模考',
            2=>'线上作答',
            3=>'课文跟读',
            4=>'单词跟读',
            5=>'报听写',
            6=>'互动教程',
        ];
        $dd = [1,2,3,4,5,6];
        foreach ($dd as $k=>$v) {
            $missionInfo[$k]['title'] = $missionTxt[$v];
            $missionInfo[$k]['num'] = 12-$v;
            $missionInfo[$k]['done_lv'] = round(12+$v+0.222,1);
            $missionInfo[$k]['score_lv'] = round(12+$v+0.32,1);
            $missionInfo[$k]['excellent_lv'] = round(12+$v+0.42,1);
            $missionInfo[$k]['pass_lv'] = round(12+$v+0.435,1);
        }
        $data = [
            'done'=>10,
            'class_sort_done'=>2,
            'fix'=>9,
            'done_fix'=>10,
            'lx_self'=>44,
            'class_sort_self'=>5,
            'mission_done_lv'=>19.8,
            'mission_done_lv_last'=>-19.8,
            'mission_get_score_lv'=>13.8,
            'mission_get_score_lv_last'=>14.8,
            'date_list'=>['4.1','4.2','4.3','4.4','4.5','4.6'],
            'self_score_list'=>[8.5,88.5,93.5,6.3,66.3,32],
            'class_score_list'=>[6.5,68.5,73.5,10.3,78.3,54],
            'mission_info'=>$missionInfo
        ];
        $this->success('成功', $data);
    }

    public function getMissionMore()
    {
        $param = request()->param();
        if(empty($param['month'])){
            $param['month'] = 1;
        }
        $missionInfo = [];
        $missionTxt = [
            1=>'听说模考',
            2=>'线上作答',
            3=>'课文跟读',
            4=>'单词跟读',
            5=>'报听写',
            6=>'互动教程',
        ];
        $dd = [1,2,3,4,5,6];
        foreach ($dd as $k=>$v) {
            $missionInfo[$k]['title'] = $missionTxt[$v];
            $missionInfo[$k]['num'] = 12-$v;
            $missionInfo[$k]['time'] = $v.'h '.$v.'min '.$v.'s';
            $missionInfo[$k]['svg_score_lv'] = round(12+$v+0.222,1);
            $missionInfo[$k]['date_list'] = ['4.1','4.2','4.3','4.4','4.5','4.6'];
            $missionInfo[$k]['self_score_list'] = [8.5,88.5,93.5,6.3,66.3,32,8.5,88.5,93.5,6.3,66.3,32,8.5,88.5,93.5,6.3,66.3,32];
            $missionInfo[$k]['class_score_list'] = [6.5,68.5,73.5,10.3,78.3,54,6.5,68.5,73.5,10.3,78.3,54,6.5,68.5,73.5,10.3,78.3,54];
            $missionInfo[$k]['true_score_list'] = [6.5,68.5,73.5,10.3,78.3,54,6.5,68.5,73.5,10.3,78.3,54,6.5,68.5,73.5,10.3,78.3,54];
        }
        $this->success('成功', $missionInfo);
    }

    public function getStudyLogList()
    {
        $param = request()->param();
        if(empty($param['month'])){
            $param['month'] = 1;
        }
        $list = Mission::where(['user_id'=>$this->auth->id])->find();
        $data = [];
        for ($i=0;$i<15;$i++){
            $data[$i]['mission_id'] = $list['mission_id'];
            $data[$i]['title'] = $list['title'];
            $data[$i]['question_type'] = $list['question_type'];
            $data[$i]['source_id'] = $list['source_id'];
            $data[$i]['question_source_type'] = $list['question_source_type'];
            $data[$i]['score'] = $list['score'];
            $data[$i]['formatter_time'] = date('m/d H:i',$list['updatetime']);
        }

//        学习记录
        $res = [
            '本月'=>$data,
            '3月'=>$data,
            '1月'=>$data,
            '2023.12'=>$data,
            '2023.11'=>$data,
            '2022.11'=>$data,
        ];
        $this->success('成功', $res);
    }



    /**
     * 查找二维数组指定的ID
     * @param $array
     * @param $key
     * @param $value
     * @return array
     */
    function searchArray($array, $key, $value) {
        return array_filter($array, function ($item) use ($key, $value) {
            if(isset($item[$key]) && $item[$key] == $value){
                return $value;
            }
            return null;
        });
    }

    public function getSourceSonList($id='5507616682740237366')
    {
        //跟读资源表
        $rr = Db::name('repeat_resources')->where('versionId',$id)->find();
        $rr['gunzipResPath_full'] = fileurl($rr['gunzipResPath'],true);
        return json_decode(file_get_contents($rr['gunzipResPath_full'].'/resource/resource.json'),true);
    }

    public function getSourceInfo($id='5507616682740237366',$key=3,$infoId='4775126870686339757')
    {
        $searchKey = 'wId';
        if($key==1){
            $hsr = Db::name('hear_say_resources')->where('versionId',$id)->find();
            $hsr['gunzipResPath_full'] = fileurl($hsr['gunzipResPath'],true);

           return json_decode(file_get_contents($hsr['gunzipResPath_full'].'/resource/resource_h5.json'),true);
//            var_dump(json_encode($res,JSON_UNESCAPED_UNICODE));exit;
//            $data = [];
//            foreach ($res['parts'] as $k=>$v) {
//                $data[$k]['module_type_name'] = $v['module_type_name'];
//                $stem = [];
//                foreach ($v['children'] as $sk=>$sv){
//                    $questions = [];
//                    foreach ($sv['children'] as $qk=>$qv){
//                        $questions[$qk]['stem'] = $qv['stem'];
//                        $questions[$qk]['question_ref_sorce'] = $qv['question_ref_sorce'];
//                        $questions[$qk]['version_id'] = $qv['version_id'];
//                        $questions[$qk]['attachments'] = $qv['attachments'];
//                        $questions[$qk]['ref_info'] = $qv['ref_info'];
//
//                    }
//                    $stem = $questions;
//                }
//
//                $data[$k]['info'] =$stem;
//                return $data;
//            }
        }
        if($key==3){
            $rr = Db::name('repeat_resources')->where('versionId',$id)->find();
            $rr['gunzipResPath_full'] = fileurl($rr['gunzipResPath'],true);
            $res = json_decode(file_get_contents($rr['gunzipResPath_full'].'/resource/resource.json'),true);
//            $searchKey = 'wId';
        }
        if(empty($res)){
            return null;
        }
        $findRes = $this->searchArray($res,$searchKey,$infoId)??[];
        foreach ($findRes as $v) {
            return $v;
        }
    }

    /**答题保存公用
     * @return void
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function saveMissionAnswer()
    {
        $param = request()->param();
//        $this->auth->id = 2;
        $answerModel = new RecitingQuestionAnswer();
        //查询是否已经回答过这个小题
        $infoWhere = [
            'user_id'=>$this->auth->id,
            'mission_id'=>$param['mission_id'],
            'source_id'=>$param['source_id'],
            'son_source_id'=>$param['son_source_id']??0,
        ];
        $infoWhere['version_id'] = $param['version_id']??0;
        $infoWhere['son_version_id'] = $param['son_version_id']??0;
        $answerInfo = RecitingQuestionAnswer::where($infoWhere)->find();
        //直接保存即可
        $confirmField = [
            'score'=>$param['score']??0,
            'wz_score'=>$param['wz_score']??0,
            'll_score'=>$param['ll_score']??0,
            'zq_score'=>$param['zq_score']??0,
            'sort'=>$param['sort']??0,
            'answer_remark'=>$param['answer_remark']??'',
            'source_url'=>$param['source_url']??'',
            'full_score'=>$param['full_score']??100,
            'son_version_id'=>$param['son_source_id']??'',
        ];
        $confirmField['true_answer_body'] = $param['true_answer_body'];
        $confirmField['type'] = $param['qtype'];
        $confirmField['answer_options_id'] = $param['answer_options_id']??"";
        $confirmField['true_answer_options_id'] = $param['true_answer_options_id']??"";
        switch ($param['qtype']) {
            //1读，上传音频 2选择（含多选） 3填空,听写（含一小题多空） 4.一个空但是有多个答案的 5.造句
            case 1:
//                $confirmField['score'] = $param['true_answer_body']===$param['answer_remark']?$confirmField['full_score']:0;
                break;
            case 2:
                $answers = explode('|',$param['answer_options_id']);
                $true_answers = explode('|',$param['true_answer_options_id']);
                $count = 0;
                foreach ($answers as $v) {
                    if(!empty($v)) {
                        if(in_array($v,$true_answers)){
                            $count+=1;
                        }
                    }
                }
                $trueCount = count($true_answers);
                if($trueCount==0){
                    $trueCount=1;
                }
                $confirmField['score'] = round($count*($confirmField['full_score']/$trueCount),1);
                break;
            case 3:
                $answers = explode('|',$param['answer_remark']);
                $true_answers = explode('|',$param['true_answer_body']);
                $count = 0;
                foreach ($answers as $v) {
                    if(!empty($v)) {
                        if(in_array($v,$true_answers)){
                            $count+=1;
                        }
                    }
                }
                $trueCount = count($true_answers);
                if($trueCount==0){
                    $trueCount=1;
                }
                $confirmField['score'] = round($count*($confirmField['full_score']/$trueCount),1);
                break;
            case 4:
                $true_answers = explode('|',$param['true_answer_body']);
                if(in_array($confirmField['answer_remark'],$true_answers)){
                    $confirmField['score'] = $confirmField['full_score'];
                }
                break;

            case 5:
                //造句
                $true_answers = explode('|',$param['true_answer_body']);
                if(in_array($confirmField['answer_remark'],$true_answers)){
                    $confirmField['score'] = $confirmField['full_score'];
                }
                break;
        }
        if(!$answerInfo){
            $insertData = [
                'mission_id'=>$param['mission_id']??0,
                'son_source_id'=>$param['son_source_id']??0,
                'source_id'=>$param['source_id']??0,
                'version_id'=>$param['version_id']??0,
                'question_type'=>$param['question_type']??0,
                'user_id' => $this->auth->id,
            ];
            $answerModel->save(array_merge($insertData,$confirmField));
        } else {
            //说明重复答题了，直接做修改
            RecitingQuestionAnswer::where([
                'user_id'=>$this->auth->id,
                'mission_id'=>$param['mission_id'],
                'source_id'=>$param['source_id'],
                'son_source_id'=>$param['son_source_id'],
            ])->update($confirmField);
        }

        $this->success('提交成功',$sendRes??null);
    }

    /**答题保存公用 -戎工
     * @return void
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function saveAnswer()
    {
        $param = request()->param();
//        $this->auth->id = 2;
        $answerModel = new RecitingQuestionAnswer();
        //查询是否已经回答过这个小题
        $infoWhere = [
            'user_id'=>$this->auth->id,
            'mission_id'=>$param['mission_id'],
            'source_id'=>$param['source_id'],
            'son_source_id'=>$param['son_source_id']??0,
        ];
        
        // $infoWhere['son_version_id'] = $param['son_version_id']??0;
        $answerInfo = RecitingQuestionAnswer::where($infoWhere)->find();
        //直接保存即可
        $confirmField = [
            'score'=>$param['score']??0,
            'wz_score'=>$param['wz_score']??0,
            'll_score'=>$param['ll_score']??0,
            'zq_score'=>$param['zq_score']??0,
            'answer_remark'=>$param['answer_remark']??'',
            'source_url'=>$param['source_url']??'',
            'full_score'=>$param['full_score']??100,
        ];
        $confirmField['true_answer_body'] = $param['true_answer_body'];
        $confirmField['type'] = $param['qtype'];
        $confirmField['answer_options_id'] = $param['answer_options_id']??"";
        $confirmField['true_answer_options_id'] = $param['true_answer_options_id']??"";
        switch ($param['qtype']) {
            //1读，上传音频 2选择（含多选） 3填空,听写（含一小题多空） 4.一个空但是有多个答案的 5.造句
            case 1:
//                $confirmField['score'] = $param['true_answer_body']===$param['answer_remark']?$confirmField['full_score']:0;
                break;
            case 2:
                $answers = explode('|',$param['answer_options_id']);
                $true_answers = explode('|',$param['true_answer_options_id']);
                $count = 0;
                foreach ($answers as $v) {
                    if(!empty($v)) {
                        if(in_array($v,$true_answers)){
                            $count+=1;
                        }
                    }
                }
                $trueCount = count($true_answers);
                if($trueCount==0){
                    $trueCount=1;
                }
                $confirmField['score'] = round($count*($confirmField['full_score']/$trueCount),1);
                break;
            case 3:
                $answers = explode('|',$param['answer_remark']);
                $true_answers = explode('|',$param['true_answer_body']);
                $count = 0;
                foreach ($answers as $v) {
                    if(!empty($v)) {
                        if(in_array($v,$true_answers)){
                            $count+=1;
                        }
                    }
                }
                $trueCount = count($true_answers);
                if($trueCount==0){
                    $trueCount=1;
                }
                $confirmField['score'] = round($count*($confirmField['full_score']/$trueCount),1);
                break;
            case 4:
                $true_answers = explode('|',$param['true_answer_body']);
                if(in_array($confirmField['answer_remark'],$true_answers)){
                    $confirmField['score'] = $confirmField['full_score'];
                }
                break;

            case 5:
                //造句
                $true_answers = explode('|',$param['true_answer_body']);
                if(in_array($confirmField['answer_remark'],$true_answers)){
                    $confirmField['score'] = $confirmField['full_score'];
                }
                break;
        }
        $productarr = [
            1=>'hear_say',
            2=>'listening',
            3=>'repeat',
            4=>'writing',
            5=>'soundmark',
            6=>'model',
            7=>'new_concept',
            8=>'_black_plum',
        ];
        $pid = Db::name($productarr[$param['question_type']].'_resources')->where('versionId',$param['source_id'])->value('productId');
        if(!$answerInfo){
            $insertData = [
                'mission_id'=>$param['mission_id']??0,
                'question_type'=>$param['question_type']??0,
                'pid'=>$pid??0,
                'source_id'=>$param['source_id']??0,
                'son_source_id'=>$param['son_source_id']??0,
                'user_id' => $this->auth->id,
            ];
            $answerModel->save(array_merge($insertData,$confirmField));
        } else {
            //说明重复答题了，直接做修改
            RecitingQuestionAnswer::where([
                'user_id'=>$this->auth->id,
                'mission_id'=>$param['mission_id'],
                'source_id'=>$param['source_id'],
                'son_source_id'=>$param['son_source_id'],
            ])->update($confirmField);
        }

        $this->success('提交成功',$sendRes??null);
    }

    //小题答案验证
    public static function answerVerify($ptype,$source_id,$son_source_id,$answer_id){
        $productarr = [
            1=>'hear_say',
            2=>'listening',
            3=>'repeat',
            4=>'writing',
            5=>'soundmark',
            6=>'model',
            7=>'new_concept',
            8=>'_black_plum',
        ];
        $gunzipResPath = cdnurl(Db::name($productarr[$ptype].'_resources')->where('versionId',$source_id)->value('gunzipResPath'),true);
        $resource = json_decode(file_get_contents($gunzipResPath.'/resource/resource.json'),true);
        
    }

    public static function secondsToHoursMinutes($seconds) {
        $hours = floor($seconds / 3600);
        $minutes = floor(($seconds % 3600) / 60);
        $seconds = $seconds % 60;
        $str = '';
        if(!empty($hours)){
            $str.=$hours."h ";
        }
        if(!empty($minutes)){
            $str.=$minutes."min ";
        }
        if(!empty($seconds)){
            $str.=$seconds."s";
        }
        return $str;
    }

    public function saveMission()
    {
        $param = input();
        $model = new Mission();
        $mission_id = input('mission_id');
        $score = input('score');
        $question_type = input('question_type');
        $question_num = input('question_num');
        $source_id = input('source_id');
        $json = input('json');
        // if (!$mission_id) {
        //     $this->error('参数有误');
        // }
        $module = '';
        if ($source_id&&$question_type) {
            $sourcearr = [
                1=>'hear_say',
                2=>'listening',
                3=>'repeat',
                4=>'writing',
                5=>'soundmark',
                6=>'model',
                7=>'new_concept',
                8=>'_black_plum',
            ];
            $modulename = Db::name($sourcearr[$question_type].'_resources')->where('versionId',$source_id)->value('moduleName');
            $missionTxt = [
                1=>'听说模考',
                2=>'单词跟读',
                3=>'课文跟读',
                4=>'线上作答',
                5=>'报听写',
            ];
            foreach ($missionTxt as $vv) {
                if (strpos($modulename,$vv)!==false) {
                    $module = $vv;
                }
            }
        }
        $homework = [];
        if ($mission_id) {
            $homework = Homework::where(['id'=>$mission_id])->find();
            //查询是否已经回答过这个小题
            //$this->auth->id = 2;
            $missionInfo = Mission::where([
                'user_id'=>$this->auth->id,
                'mission_id'=>$mission_id,
            ])->find();
            //直接保存即可
            $answerModel = new RecitingQuestionAnswer();
            $detailSum = $answerModel->where([
                'user_id'=>$this->auth->id,
                'mission_id'=>$mission_id??0,
            ])->field('sum(score) as score_all,count(*) as q_number,MAX(createtime) - MIN(createtime) AS use_time')->find();
        }else{
             $missionInfo = Mission::where([
                'user_id'=>$this->auth->id,
                'source_id'=>$source_id,
            ])->find();
            //直接保存即可
            $answerModel = new RecitingQuestionAnswer();
            $detailSum = $answerModel->where([
                'user_id'=>$this->auth->id,
                'source_id'=>$source_id??0,
            ])->field('sum(score) as score_all,count(*) as q_number,MAX(createtime) - MIN(createtime) AS use_time')->find();
        }

        if ($missionInfo) {
            $object = "answer/json/".$missionInfo->id.".json";
        } else {
            $lastId=Mission::order('id desc')->value('id') + 1;
            $object = "answer/json/".$lastId.".json";
        }
        //上传json到oss
        try{
            $config = get_addon_config('alioss');
            $bucket = $config['bucket']; //创建的项目
            $ossClient = new OssClient($config['accessKeyId'], $config['accessKeySecret'], $config['endpoint']);
            $ossClient->putObject($bucket, $object, $json);
        } catch(OssException $e) {
            $this->error($e->getMessage().'请稍后再试！');
        }

        //暂定评分计算逻辑为 (score_all/question_num)
        if(!isset($question_num)||empty($question_num)){
            if($question_type==3){
                $question_num = count($this->getSourceSonList($source_id));
            }
        }
        $answer_num = $detailSum['q_number']??0;
//        if(empty($score'])){
//            $score'] = round($detailSum['score_all']/$question_num']??5,1);
//        }
        $score = $detailSum['score_all'];
        //答题用时
        $use_time = self::secondsToHoursMinutes($detailSum['use_time']??0);

        $confirmField = [
            'score'=>round($score,1)??0,
            'answer_num'=>$answer_num??0,
            'title' => $homework['name']??'',
            'use_time' => $use_time,
            'is_done'=>$answer_num>=$question_num?1:2,
            'question_source_type'=>$question_source_type??0
        ];
        if(!$missionInfo){
            $insertData = [
                'mission_id'=>$mission_id??0,
                'mission_type'=>$homework['type']??0,
                'class_id'=>$this->auth->class_id,
                'gread_id'=>$this->auth->grade_id,
                'source_id'=>$source_id??'',
                'module'=>$module,
                'score'=>$score??0,
                'json'=>$json??null,
                'question_num'=>$question_num??5,
                'user_id' => $this->auth->id,
                'question_type' => $question_type??0,
            ];
            $model->save(array_merge($insertData,$confirmField));
        } else {
            //说明重复答题了，直接做修改
            Mission::where([
                'user_id'=>$this->auth->id,
                'mission_id'=>$mission_id,
                'json'=>$json,
            ])->update($confirmField);
        }
        $msg = $score>=100?'SIX SIX SIX':'You can do better!';
        $sendRes = [
            // TODO: 完善主表相关关联
            'question_num'=>$question_num,
            'answer_num'=>$answer_num,
            'score'=>round($score,1)??0,
            'msg'=>$msg,
            'mission_id' => $mission_id,
        ];


        $this->success('作业提交成功',$sendRes);
    }

    /**
     * 单词答题
     * @param $missionId
     * @return bool|\PDOStatement|string|\think\Collection
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function getWordsAnswerList($missionId=0)
    {
        $answerModel = new RecitingQuestionAnswer();
        $list = $answerModel->where([
            'user_id'=>$this->auth->id,
            'mission_id'=>$missionId,
        ])->field('source_id,son_source_id,mission_id,score,wz_score,zq_score,
        ll_score,answer_remark,true_answer_body,source_url,question_type,answer_options_id,true_answer_options_id,full_score',
        )->select();
        foreach ($list as $k=>$v){
//            if($v['question_type']==3){
//                $sourceInfo = $this->getSourceInfo($v['source_id'],$v['question_type'],$v['son_source_id']);
//                //单词类型
//                $list[$k]['content'] = $sourceInfo['words']??'';
//                $list[$k]['symbol'] = $sourceInfo['symbol']??'';
//                $list[$k]['pretations'] = $sourceInfo['pretations']??'';
//            }

//            if($v['question_type']==1){
//               var_dump($sourceInfo);
//            }


            if($v['score']==0){
                $list[$k]['color'] = 1;
            }else if($v['score']<60){
                $list[$k]['color'] = 2;
            }elseif ($v['score']<80){
                $list[$k]['color'] = 3;
            }elseif ($v['score']>=80){
                $list[$k]['color'] = 4;
            }
        }
        return $list;
    }

    /**获取答题结果
     * @return void
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function getMissionAnswerDetail()
    {
        $param = request()->param();
        $detailList = $this->getWordsAnswerList($param['mission_id']??0);
        if(!$detailList){
            $detailList = null;
        }
        $this->success('获取成功',$detailList);
    }

    public function getMissionDetail()
    {
        $param = request()->param();
        $model = new Mission();
        //查询是否已经回答过这个小题
        $missionWhere = [
            'user_id'=>$this->auth->id,
            'mission_id'=>$param['mission_id'],
            'gread_id'=>$param['gread_id'],
            'class_id'=>$param['class_id'],
        ];
        $missionInfo = Mission::where($missionWhere)->find();
        if(empty($missionInfo)){
            $this->error('任务信息不存在');
        }
        $selfInfo = [
            'score'=>$missionInfo['score']??0,
            'score_lv'=>($missionInfo['score']/$missionInfo['full_score']*100).'%',
        ];
        unset($missionWhere['user_id']);
        $count = Mission::where($missionWhere)->field('MAX(score) as max_score,count(*) as answer_num,AVG(score) as avg_score')->find();

        //查询班级前十名
        $sixStu = Mission::alias('a')->join('user b','a.user_id=b.id')->where([
            'a.mission_id'=>$param['mission_id'],
            'a.gread_id'=>$param['gread_id'],
            'a.class_id'=>$param['class_id'],
        ])->order('a.score desc')->field('b.nickname,a.score,a.user_id')->limit(0,10)->select();
        $all = [
            'max_score'=>$count['max_score'],
            'answer_num'=>$count['answer_num'],
            'avg_score'=>round($count['avg_score']),
            'done_num'=>0,
        ];
        $scoreBetween = [
            '0-20%'=>0,
            '20-40%'=>0,
            '40-60%'=>0,
            '60-70%'=>0,
            '70-80%'=>0,
            '80-90%'=>0,
            '90-100%'=>0,
        ];
        $scoreAll = Mission::where($missionWhere)->select();
        foreach ($scoreAll as $k=>$v) {
            if($v['is_done']==1){
                $all['done_num']+=1;
            }
            $lv = ($v['score']/$v['full_score'])*100;
            if($lv<20){
                $scoreBetween['0-20%']+=1;
            } elseif ($lv<40){
                $scoreBetween['20-40%']+=1;
            } elseif ($lv<60){
                $scoreBetween['40-60%']+=1;
            } elseif ($lv<70){
                $scoreBetween['60-70%']+=1;
            } elseif ($lv<80){
                $scoreBetween['70-80%']+=1;
            } elseif ($lv<90){
                $scoreBetween['80-90%']+=1;
            } elseif ($lv<100){
                $scoreBetween['90-100%']+=1;
            }
        }
        $answerList = $this->getWordsAnswerList($param['mission_id']??0);
        $redStr = 0;
        $yellowStr = 0;
        $greenStr = 0;
        foreach ($answerList as $k=>$v) {
            if($v['color']==1||$v['color']==2){
                $redStr+=1;
            }
            if($v['color']==3){
                $yellowStr+=1;
            }
            if($v['color']==4){
                $greenStr+=1;
            }
        }
        $this->success('获取成功',[
            'self_info'=>$selfInfo,
            'all'=>$all,
            'good_stu_10'=>$sixStu,
            'score_between'=>$scoreBetween,
            'full_score'=>$missionInfo['full_score']??1,
            'answer_num'=>$missionInfo['answer_num']??0,
            'use_time'=>$missionInfo['use_time']??'',
            'red_str'=>$redStr??0,
            'yellow_str'=>$yellowStr??0,
            'green_str'=>$greenStr??0,
            'answerList'=>$answerList
        ]);
    }

    public function getSetting()
    {
        $books = TextBooks::where([
            'versionId' => request()->get('version_id')
        ])->find();

        $increments = [5, 10, 25, 50];
        $incrementIndex = 0;

        $current = 0; // 当前值
        $day = 0; // 当前天数
        $increment = 0; // 当前增量

        $count = [];
        $days = [];

        while ($current < $books->wordsCount) {
            if ($day >= 10 && $day < 20) {
                $increment = $increments[1];
            } elseif ($day >= 20 && $day < 30) {
                $increment = $increments[2];
            } elseif ($day >= 30) {
                $increment = $increments[3];
            } else {
                $increment = $increments[0];
            }

            $current += $increment;

            $count[] = $current;
            $days[] = ceil($books->wordsCount / $current);

            if ($current >= $books->wordsCount)
                break;

            $day++;
        }

        array_pop($count);
        $count[] = $books->wordsCount;

        $this->success(null, [
            'days' => array_values(array_unique($days)),
            'count' => $count
        ]);
    }

    public function index()
    {
        $userRecitingPlan = new UserRecitingPlan();

        $planInfo = $userRecitingPlan->where([
            'user_id' => $this->auth->id
        ])->find();
        if (!$planInfo)
            $this->error('暂无课程选择');

        $endTime = $planInfo->createtime + ($planInfo->end_day * 86400);

        // 单词总数
        $wordsCount = $this->words->where('versionId', $planInfo->version_id)->count();

        // 已学完数
        $yesCount = $this->recitingWordsLog->alias('a')->join($this->words->getTable() . ' b', 'a.wid = b.id', 'left')
            ->where([
                'a.user_id' => $this->auth->id,
                'a.version_id' => $planInfo->version_id
            ])
            ->count();

        // 今日学习数
        $todayCount = $this->recitingWordsLog->where([
            'user_id' => $this->auth->id,
            'version_id' => $planInfo->version_id
        ])->where('createtime', '>=', strtotime(date('y-m-d')))->count();

        // 答错数
        $todayNoCount = $this->recitingWordsLog->where([
            'user_id' => $this->auth->id,
            'status' => '0',
            'version_id' => $planInfo->version_id
        ])->where('createtime', '>=', strtotime(date('y-m-d')))->count();

        // 教材
        $books = TextBooks::where([
            'versionId' => $planInfo->version_id
        ])->find();

        $result = [
            'end_day' => floor(($endTime - time()) / 86400),
            'plan_count' => $planInfo->count,
            'today_count' => $todayCount,
            'words_count' => $wordsCount,
            'yes_count' => $yesCount,
            'today_no_count' => $todayNoCount,
            'version_full_name' => $books->versionFullName
        ];

        $this->success('成功', $result);
    }

    public function updatePlan()
    {
        $data = request()->post();

        $plan = UserRecitingPlan::where([
            'user_id' => $this->auth->id
        ])->find();

        if (!$plan) {
            $data['user_id'] = $this->auth->id;
            UserRecitingPlan::create($data);
        } else {
            $plan->save($data);
        }

        $this->success("操作成功");
    }

    public function getWordsList()
    {
        $versionId = request()->get('versionId');
        if (!$versionId)
            $this->error('参数有误');

        $wordsInfo = $this->words->alias("a")
            ->join($this->recitingWordsLog->getTable() . " b", 'a.id = b.wid', 'left')
            ->whereNull('b.id')
            ->where(['a.versionId' => $versionId])
            ->field('a.interpretationId')
            ->find();

        if (!$wordsInfo)
            $this->error("没有找到数据");

        $words = $this->wordsDetails->where([
            'wId' => $wordsInfo->interpretationId,
            'versionId' => $versionId
        ])->find();

        $otherList = $this->wordsDetails->where([
            'versionId' => $versionId
        ])->where('wId', '<>', $wordsInfo->interpretationId)->orderRaw('rand()')->limit(3)->select();

        $list[] = $words;
        $list = array_merge($list, $otherList);
        shuffle($list);

        $this->success('成功', $list);
    }

    public function selectData()
    {
        $id = request()->post('id');
        $wid = request()->post('wid');

        if (!$id || !$wid)
            $this->error('参数有误');

        $detailInfo = $this->wordsDetails->where([
            'id' => $id
        ])->find();

        $status = "1";
        if ($detailInfo->wId != $wid)
            $status = "0";

        // 判断该单词是否已经答过
        $has = $this->recitingWordsLog->where([
            'user_id' => $this->auth->id,
            'wid' => $wid,
        ])->find();
        if ($has) {
            $has->wd_id = $id;
            $has->status = $status;
            $has->save();
        } else {
            $data = [
                'user_id' => $this->auth->id,
                'wid' => $wid,
                'wd_id' => $id,
                'version_id' => $detailInfo->versionId,
                'status' => $status
            ];

            $this->recitingWordsLog->save($data);
        }

        $this->success('成功', $status);
    }

    public function bookList()
    {
        $book = new TextBooks();

        $periodName = $book->group('periodName')->select();

        $result = [];
        foreach ($periodName as $name) {
            $list = $book->where([
                'periodName' => $name->periodName
            ])->order('orderNum', 'asc')->select();

            $result[$name->periodName] = $list;
        }

        $this->success(null, $result);
    }

    public function pk()
    {
        $list = $this->wordsDetails->group('words')->orderRaw("rand()")->limit(5)->select();

        $this->success(null, $list);
    }

    public function addWords()
    {
        $data = request()->post();

        $data['user_id'] = $this->auth->id;

        $model = new BrushWords();
        $model->save($data);

        $this->success(null, "成功");
    }

    public function brushWordsList() {
        $limit = request()->get('limit', 10);
        $page = request()->get('page', 1);

        $model = new BrushWords();
        $list = $model->with('wordsDetail')->where([
            'user_id' => $this->auth->id
        ])->order('createtime', 'desc')->limit($limit)->page($page)->select();

        $this->success(null, $list);
    }

    public function wordsInfo()
    {
        $id = request()->get('id', null);

        $model = new BrushWords();
        $info = $model->with('wordsDetail')->findOrFail($id);

        $this->success(null, $info);
    }
}